import React, { useState } from 'react'
import { View, Image, Text, Progress } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './MultiImageUploader.scss'
import Add from "@/assets/plus/add.png";
import { request } from '@/utils/request';

interface MultiImageUploaderProps {
  maxCount?: number
  value?: string[]
  onChange?: (urls: string[]) => void
}

interface UploadItem {
  localPath: string
  url?: string
  progress: number
  status: 'uploading' | 'success' | 'error'
}

const MultiImageUploader: React.FC<MultiImageUploaderProps> = ({
                                                                 maxCount = 9,
                                                                 value = [],
                                                                 onChange
                                                               }) => {
  const [imageList, setImageList] = useState<UploadItem[]>(
    value.map(url => ({ localPath: url, url, progress: 100, status: 'success' }))
  )

  const chooseImages = () => {
    Taro.chooseImage({
      count: maxCount - imageList.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const newItems: UploadItem[] = res.tempFilePaths.map(path => ({
          localPath: path,
          progress: 0,
          status: 'uploading'
        }))
        const updatedList = [...imageList, ...newItems].slice(0, maxCount)
        setImageList(updatedList)
        onChange?.(updatedList.filter(i => i.url).map(i => i.url!))
        await uploadImages(newItems)
      }
    })
  }

  const uploadImages = async (items: UploadItem[]) => {
    for (const item of items) {
      try {
        // Taro.uploadFile 支持上传进度，可以封装成 promise
        await new Promise<void>((resolve, reject) => {
          const uploadTask = Taro.uploadFile({
            url: request['baseURL'] + '/infra/file/upload',
            filePath: item.localPath,
            name: 'file',
            header: { Authorization: `Bearer ${Taro.getStorageSync('token')}` },
            success: (res) => {
              const data = JSON.parse(res.data)
              if (data.code && data.code !== 0) {
                item.status = 'error'
                reject(data)
              } else {
                item.status = 'success'
                item.url = data.data // 假设接口返回 url
                resolve()
              }
            },
            fail: (err) => {
              item.status = 'error'
              reject(err)
            }
          })

          uploadTask.onProgressUpdate((res) => {
            item.progress = res.progress
            setImageList(list => [...list])
          })
        })
      } catch (err) {
        Taro.showToast({ title: '上传失败', icon: 'none' })
      } finally {
        setImageList(list => [...list])
        onChange?.(imageList.filter(i => i.url).map(i => i.url!))
      }
    }
  }

  const deleteImage = (index: number) => {
    const updated = [...imageList]
    updated.splice(index, 1)
    setImageList(updated)
    onChange?.(updated.filter(i => i.url).map(i => i.url!))
  }

  return (
    <View className="multi-image-uploader">
      <View className="image-list">
        {imageList.map((item, index) => (
          <View className="image-item" key={index}>
            <Image src={item.url || item.localPath} className="image" mode="aspectFill" />
            {item.status === 'uploading' && (
              <Progress
                percent={item.progress}
                showInfo={false}
                strokeWidth={3}
                activeColor="#FE7407"
                backgroundColor="#fff"
              />
            )}
            {item.status === 'error' && (
              <View className="upload-error">上传失败</View>
            )}
            <View className="delete-btn" onClick={() => deleteImage(index)}>
              ✕
            </View>
          </View>
        ))}
        {imageList.length < maxCount && (
          <View className="image-item add-btn" onClick={chooseImages}>
            <Image src={Add} className="upload-icon" />
          </View>
        )}
      </View>
    </View>
  )
}

export default MultiImageUploader
